<template>
  <div class="pagination">
    <button :disabled="pageNo <= 1" @click="$emit('changePageNo', pageNo - 1)">
      上一页
    </button>
    <button
      v-show="startAndEndValue.start > 1"
      @click="$emit('changePageNo', 1)"
    >
      1
    </button>

    <button v-show="startAndEndValue.start > 2">···</button>

    <!-- <button
      v-for="item in startAndEndValue.end"
      :key="item"
      v-if="item >= startAndEndValue.start"
      @click="$emit('changePageNo', item)"
      :class="item === pageNo ? 'active' : ''"
    >
      {{ item }}
    </button> -->
    <button
      v-for="item in startAndEndArray"
      :key="item"
      @click="$emit('changePageNo', item)"
      :class="item === pageNo ? 'active' : ''"
    >
      {{ item }}
    </button>

    <button v-show="startAndEndValue.end < totalPages - 1">···</button>
    <button
      v-show="startAndEndValue.end < totalPages"
      @click="$emit('changePageNo', totalPages)"
    >
      {{ totalPages }}
    </button>

    <button
      :disabled="pageNo >= totalPages"
      @click="$emit('changePageNo', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>
  
  <script>
export default {
  name: "Pagination",
  props: ["continuePages", "pageNo", "totalPages", "total"],
  computed: {
    // 计算页码的连续值
    startAndEndValue() {
      const { continuePages, pageNo, totalPages } = this;
      let start = null;
      let end = null;
      if (continuePages > totalPages) {
        start = 1;
        end = pageNo;
      } else {
        //分别计算出连续值的起始值和结束值
        start = pageNo - (continuePages - 1) / 2;
        end = pageNo + (continuePages - 1) / 2;

        // 对起始值进行判断(起始值不能小于1),
        if (start < 1) {
          start = 1;
          end = continuePages;
        }
        // 对结束值进行判断(结束值不能大于totalPages),
        if (end > totalPages) {
          (end = totalPages), (start = totalPages - continuePages + 1);
        }
      }

      return { start, end };
    },

    //计算页码连续遍历的范围(可设置成一个数组)，避免v-if和v-for一起使用
    startAndEndArray() {
      // 已知起始值(startAndEndValue.start)和结束值(startAndEndValue.end)，求数组
      const { start, end } = this.startAndEndValue;
      const arr = [];
      for (let i = start; i <= end; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
};
</script>
  
  <style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>